import nats from 'node-nats-streaming';
import { TicketCreatedPublisher } from './events/ticket-created-publisher';

console.clear();
const stan = nats.connect('ticketing', 'abc', {
    url: 'http://localhost:4222',
});

stan.on('connect', async () => {
    console.log('Publisher connected to NATS');

    const publisher = new TicketCreatedPublisher(stan);

    try {
        await publisher.publish({
            id: '12345',
            price: 20,
            title: 'testtitleabc'
        });
    }
    catch (err) {
        console.log(err);
    }

    // const data = JSON.stringify({
    //     'id': '123',
    //     'title': 'testtitle',
    //     'price': 100
    // });
    // //广播消息
    // stan.publish('ticket:created', data, (err, guid) => {
    //     if (err) {
    //         console.log('publish failed: ' + err);
    //     }
    //     else {
    //         console.log('publish message with guid: ' + guid);
    //     }
    // });

    //订阅消息
    // const subscribeOpts = stan.subscriptionOptions().setStartWithLastReceived();
    // const subscription = stan.subscribe('ticket:created', subscribeOpts);
    // subscription.on('message', (msg: Message) => {
    //     console.log('Received a message: [' + msg.getSequence() + '] ' + msg.getData());
    // });
});

